<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>添加企业</span>
      </div>
      <div class="right">
        黑马程序员
      </div>
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="ruleForm" label-width="100px" :model="addForm" :rules="addfromrules">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option v-for="item in industryInfo" :key="item.industryCode" :label="item.industryName" :value="item.industryCode" />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseId">
              <el-upload
                class="avatar-uploader"
                action="https://api-hmzs.itheima.net/tj/upload"
                :headers="headertype"
                :data="{type:'businessLicense'}"
                name="file"
                :on-success="filesuccess"
                :file-list="filelist"
                :before-upload="uploadbeforefile"
                :on-remove="removefile"
                :on-error="errorfile"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar el-upload-list__item-thumbnail">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button>重置</el-button>
        <el-button type="primary" @click="editenterprise">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { addenterpriseApi, getIndustryList, uploadIndustryFileAPI } from '@/apis/Park'
import { Message } from 'element-ui'
import router from '@/router'
export default {
  data() {
    return {
      addForm: {
        name: '', // 企业名称
        legalPerson: '', // 法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 所在行业
        contact: '', // 企业联系人
        contactNumber: '', // 联系人电话
        businessLicenseUrl: '', // 营业执照url
        businessLicenseId: '' // 营业执照id
      },
      //   行业信息
      industryInfo: [],
      //  回显图片路径
      imageUrl: '',
      //   上传的文件列表
      filelist: [],
      //   表单验证规则
      addfromrules: {
        name: [
          { required: true, message: '请输入企业名称', trigger: 'blur' }
        ],
        legalPerson: [
          { required: true, message: '请输入法人名称', trigger: 'blur' }
        ],
        registeredAddress: [
          { required: true, message: '请输入注册地址', trigger: 'blur' }
        ],
        industryCode: [
          { required: true, message: '请输入所在行业', trigger: 'blur' }
        ],
        contact: [
          { required: true, message: '请输入企业联系人', trigger: 'blur' }
        ],
        contactNumber: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        businessLicenseId: [
          { required: true, message: '请输入上传文件', trigger: 'blur' }
        ]

      },
      headertype: {
        'Authorization': `Bearer ${this.$store.state.user.token}`
      }
    }
  },
  created() {
    // 获取所在行业
    // console.log(this.$store.state.user.token)
    this.getIndustryinfo()
  },
  methods: {
    // 获取行业信息
    async getIndustryinfo() {
      const res = await getIndustryList()
      this.industryInfo = res.data
    },
    // 上传文件
    async uploadIndustryFile(data) {
      const fileformat = new FormData()
      fileformat.append('file', data.file)
      fileformat.append('type', 'businessLicense')

      console.log(fileformat)
      const res = await uploadIndustryFileAPI(fileformat)
      this.imageUrl = res.data.url
      console.log(res)
      this.addForm.businessLicenseUrl = res.data.url
      this.addForm.businessLicenseId = res.data.id
      console.log(this.imageUrl, this.addForm.businessLicenseUrl, this.addForm.businessLicenseId)

      this.filelist = [{
        name: data.file.name,
        url: res.data.url
      }]

      this.$refs.ruleForm.validateField('businessLicenseId')
    },
    // 上传文件之前校验文件类型
    uploadbeforefile(file) {
      const filetype = ['image/jpeg', 'image/png']
      const isJpg = filetype.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJpg) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJpg && isLt2M
    },
    // 点击确认
    editenterprise() {
      this.$refs.ruleForm.validateField('businessLicenseId')
      this.$refs.ruleForm.validate(async(ishow) => {
        if (!ishow) {
          Message.error('请输入正确的信息')
          return
        }
        const res = await addenterpriseApi(this.addForm)
        Message.success(res.msg)
        router.back()
      })
    },
    // 文件上传成功之后的函数
    filesuccess(res) {
      this.addForm.businessLicenseUrl = res.data.url
      this.addForm.businessLicenseId = res.data.id
      this.imageUrl = res.data.url
      //   console.dir(this.imageUrl, this.addForm.businessLicenseUrl, this.addForm.businessLicenseId)

      this.filelist = [{
        name: res.data.name,
        url: res.data.url
      }]

      this.$refs.ruleForm.validateField('businessLicenseId')
    },
    // 移除文件
    removefile() {
      this.imageUrl = ''
      this.filelist = []
    },
    //   文件上传失败
    errorfile() {
      Message.error('文件上传失败，请联系管理员')
    }
  }

}
</script>

  <style scoped lang="scss">

  .avatar-uploader ::v-deep .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .add-enterprise {
    background-color: #f4f6f8;
    height: 100vh;

    .add-header {
      display: flex;
      justify-content: space-between;
      padding: 0 20px;
      height: 64px;
      line-height: 64px;
      font-size: 16px;
      font-weight: bold;
      background-color: #fff;

      .left {
        span {
          margin-right: 4px;
        }
        .arrow{
          cursor: pointer;
        }
      }

      .right {
        text-align: right;
      }
    }

    .add-main {
      background: #f4f6f8;
      padding: 20px 130px;

      .form-container {
        background-color: #fff;
        .title {
          height: 60px;
          line-height: 60px;
          padding-left:20px;
        }
        .form {
          margin-bottom: 20px;
          padding: 20px 65px 24px;
          .el-form{
            display: flex;
            flex-wrap: wrap;
            .el-form-item{
              width: 50%;
            }
          }
        }
      }
    }

    .add-footer {
      position: fixed;
      bottom: 0;
      width: 100%;
      padding: 24px 50px;
      color: #000000d9;
      font-size: 14px;
      background: #fff;
      text-align: center;
    }
  }
  </style>
